package hz.mobileproject.pda.callroll.manger;


import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.blankj.utilcode.util.LogUtils;

import java.util.ArrayList;
import java.util.List;

import hz.mobileproject.pda.db.DBManager;
import hz.mobileproject.pda.entity.PrisonerPicBean;
import hz.mobileproject.pda.callroll.entity.CallRollPhotoUpdateEntity;
import hz.mobileproject.pda.callroll.entity.PhotoPathIdEntity;
import hz.mobileproject.pda.entity.response.Response_loadPrisonerList;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.network.PhotoDownLoadNetWork;
import hz.mobileproject.pda.utils.FileUtils;
import hz.mobileproject.pda.callroll.utils.BitmapUtil;

/**
 * Created by hasee on 2017/10/30.
 * 本地离线底库更新
 */
public class PhotoUpdateMgr {

    private final static String TAG = PhotoUpdateMgr.class.getSimpleName();

    public static final int MESSAGE_WHAT_UPDATE_START = 3;
    public static final int MESSAGE_WHAT_UPDATE_FINISH = 4;
    public static final int MESSAGE_WHAT_UPDATE_ITEM = 5;
    public static final String PIC_PATH_NAME = "prisonerPhoto";

    public static final String IMG_URL_PREX = "/" +Constance.BASE_URL +"/rollCall/queryPrisonerPhoto?prisoner_id=";

    private static PhotoUpdateMgr mInstance;

    private Handler mHandler;

    private Context mContext;

    private int mintUpdateNum;

    private boolean mbIsNeedDelete;

    private List<PhotoPathIdEntity> mLoadPhotoList = new ArrayList<>();

    private List<CallRollPhotoUpdateEntity> mServicePhotoList = new ArrayList<>();

    private PhotoUpdateMgr(Context context){
        mContext = context;
    }

    public static PhotoUpdateMgr getInstance(Context context){
        if (null == mInstance){
            mInstance = new PhotoUpdateMgr(context);
        }
        return mInstance;
    }

    public void updatePhoto(final List<Response_loadPrisonerList> prisonerList, Handler handler, boolean isNeedDelete){

        mHandler = handler;

        mintUpdateNum = 0;

        mbIsNeedDelete = isNeedDelete;

        initServicePhotoList(prisonerList);

        new Thread(new Runnable() {
            @Override
            public void run() {
                List<CallRollPhotoUpdateEntity> localPhotoList = getLocalPhotoList(true);
                List<CallRollPhotoUpdateEntity> updateList = comparePhotoList(mServicePhotoList, localPhotoList);
                int size = updateList.size();
                LogUtils.i(TAG, "update pic size = " + size);

                sendMesToMain(MESSAGE_WHAT_UPDATE_START, mintUpdateNum, size);
                if(updateList.size()>0){
                    for (int i=0;i<updateList.size();i++){
                        String path = updateList.get(i).getPath();
                        String id = updateList.get(i).getPhotoId();
                        String url = updateList.get(i).getUrl();
                        boolean isDelete = updateList.get(i).isDelete();

                        if(isDelete){
                            if (mbIsNeedDelete){//批次号变化时进行删除操作
                                //TODO 本地删除(删除文件，删除数据库条目)
                                BitmapUtil.deleteImageFile(path);
                                PrisonerPicBean delBean = DBManager.getInstance(mContext).queryPrisonerPicBean(id);
                                DBManager.getInstance(mContext).deletePrisonerPicBean(delBean);
                            }
                        }else{
                            //TODO 下载至本地(下载文件，插入数据库条目)
                            PhotoDownLoadNetWork netWork = new PhotoDownLoadNetWork();
                            boolean isSuccess = netWork.downPic(url, path);
                            if(isSuccess){
                                PrisonerPicBean addBean = new PrisonerPicBean();
                                addBean.setLocalPic(path);
                                addBean.setPrisoner_id(id);
                                DBManager.getInstance(mContext).insertPrisonerPicBeanList(addBean);
                            }else {
                                //TODO 单张图片下载失败的处理
                                //TODO 结束判断mintUpdateNum是否为size，否则重新更新一遍
                                continue;
                            }
                        }
                        mintUpdateNum++;
                        sendMesToMain(MESSAGE_WHAT_UPDATE_ITEM, mintUpdateNum, size);
                    }
                }

                if (mintUpdateNum == updateList.size()){
                    //重新将本地需点照片存入列表
                    getLocalPhotoList(false);
                    sendMesToMain(MESSAGE_WHAT_UPDATE_FINISH, mintUpdateNum, size);
                    mHandler = null;
                }else {
                    updatePhoto(prisonerList, mHandler, mbIsNeedDelete);
                }
            }
        }).start();
    }

    /**
     * 给主线程回调
     */
    private void sendMesToMain(int what, int curr, int size){
        if(mHandler != null){
            Message mes = new Message();
            mes.what = what;
            mes.obj = "update";
            mes.arg1 = curr;
            mes.arg2 = size;
            mHandler.sendMessage(mes);
        }
    }

    /**
     * 初始化服务端的集合
     * @param prisonerList
     */
    private void initServicePhotoList(List<Response_loadPrisonerList> prisonerList) {
        mServicePhotoList.clear();
        for (int i=0; i<prisonerList.size(); i++){
            CallRollPhotoUpdateEntity updateEntity = new CallRollPhotoUpdateEntity();
            updateEntity.setDelete(false);
            updateEntity.setPhotoId(prisonerList.get(i).getPrisoner_id());
            //TODO 服务器图片URL
            String url =        Constance.BASE_URL + IMG_URL_PREX + prisonerList.get(i).getPrisoner_id();
            updateEntity.setUrl(url);
            updateEntity.setPath(FileUtils.getAppPath(PIC_PATH_NAME) + prisonerList.get(i).getPrisoner_id() + ".jpg");
            mServicePhotoList.add(updateEntity);
        }
    }

    /**
     * 查询数据库得到犯人照片ID集合
     * @return
     */
    private List<CallRollPhotoUpdateEntity> getLocalPhotoList(boolean isNeedReturn) {
        mLoadPhotoList.clear();
        List<PrisonerPicBean> prisonerPicBeen = DBManager.getInstance(mContext).queryPrisonerPicList();
        List<CallRollPhotoUpdateEntity> callRollPhotoUpdateEntityList = new ArrayList<>();
        if(prisonerPicBeen.size()>0){
            for(PrisonerPicBean bean : prisonerPicBeen){
                if (isNeedReturn){
                    CallRollPhotoUpdateEntity callRollPhotoUpdateEntity = new CallRollPhotoUpdateEntity();
                    callRollPhotoUpdateEntity.setDelete(true);
                    callRollPhotoUpdateEntity.setPath(bean.getLocalPic());
                    callRollPhotoUpdateEntity.setPhotoId(bean.getPrisoner_id());
                    callRollPhotoUpdateEntity.setUrl(IMG_URL_PREX + bean.getPrisoner_id());
                    callRollPhotoUpdateEntityList.add(callRollPhotoUpdateEntity);
                }else {
                    PhotoPathIdEntity photoPathIdEntity = new PhotoPathIdEntity();
                    photoPathIdEntity.setId(bean.getPrisoner_id());
                    photoPathIdEntity.setPhotoPath(bean.getLocalPic());
                    mLoadPhotoList.add(photoPathIdEntity);
                }
            }
        }
        return callRollPhotoUpdateEntityList;
    }

    /**
     * 获取需点犯人图片列表
     * @return
     */
    public List<PhotoPathIdEntity> getLoadPhotoList(){
        List<PhotoPathIdEntity> photoPathIdList = new ArrayList<>();
        photoPathIdList.addAll(mLoadPhotoList);
        //清除集合，减少内存占用
        mLoadPhotoList.clear();
        return photoPathIdList;
    }

    /**
     * 对比服务器与本地数据得到需要更新的数据
     * @param servicePhotoList
     * @param localPhotoList
     * @return
     */
    private List<CallRollPhotoUpdateEntity> comparePhotoList(List<CallRollPhotoUpdateEntity> servicePhotoList
            , List<CallRollPhotoUpdateEntity> localPhotoList) {
        for(int i=servicePhotoList.size()-1;i>=0;i--){
            for(int j=localPhotoList.size()-1;j>=0;j--){
               if(localPhotoList.get(j).getPhotoId().equals(servicePhotoList.get(i).getPhotoId())) {
                    localPhotoList.remove(j);
                    servicePhotoList.remove(i);
                    break;
               }
            }
        }
        List<CallRollPhotoUpdateEntity> list = new ArrayList<>();
        list.addAll(servicePhotoList);
        list.addAll(localPhotoList);
        return list;
    }
}
